package cn.byapps.master.schedule;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import cn.byapps.master.dao.TaskRecordMapper;
import cn.byapps.master.entity.TaskRecord;
import lombok.extern.slf4j.Slf4j;

//@Component
@Transactional
@Slf4j
//@EnableScheduling
public class TaskCoudFileStore implements SchedulingConfigurer {
	@Value("${accessKey}")
	private String accessKey;// = "0o2MS26kFvP0vQPXIyk8TXdo6sIS1l3PRwES4Gwz";
	@Value("${secretKey}")
	private String secretKey;// = "WzafRljF_f_FEvv5TI_LaC7xTlbge9gPJTWQhrfW";
	@Value("${downloadPath}")
	private String downloadPath;
	@Value("${bucket}")
	private String bucket;// = "byapps";
	@Value("${cron}")
	private String cron;

	@Autowired
	private TaskRecordMapper taskRecordMapper;

	public void tranforeFile() {
		 System.out.println("基于接口SchedulingConfigurer的动态定时任务:"
                 + LocalDateTime.now() + "，线程名称：" + Thread.currentThread().getName()
                 + " 线程id：" + Thread.currentThread().getId());
		log.error("accessKey = " + accessKey);
		log.error("secretKey = " + secretKey);
		
		log.error("downloadPath = " + downloadPath);
		log.error("bucket = " + bucket);
		log.error("cron = " + cron);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 System.out.println("++++++++++++++++++++"
                 + LocalDateTime.now() + "，线程名称：" + Thread.currentThread().getName()
                 + " 线程id：" + Thread.currentThread().getId());
		// 构造一个带指定Region对象的配置类
		Configuration cfg = new Configuration(Region.huanan());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		// 上传至七牛云
		List<TaskRecord> list = taskRecordMapper
				.selectList(new QueryWrapper<TaskRecord>().lambda().notLike(TaskRecord::getImgPath, downloadPath));
		for (TaskRecord task : list) {
			String localFilePath = task.getImgPath();
			File file = new File(localFilePath);
			if (!file.exists()) {
				continue;
			}
			String key = localFilePath.substring(localFilePath.lastIndexOf(File.separator) + 1, localFilePath.length());
			try {
				Response response = uploadManager.put(localFilePath, key, upToken);
				// 解析上传成功的结果
				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
				log.info("hash = " + putRet.hash);
				log.info("key = " + putRet.key);
				task.setImgPath(downloadPath + "/" + key);
				taskRecordMapper.updateById(task);
				// 删除文件
				file.delete();
			} catch (QiniuException ex) {
				Response r = ex.response;
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					// ignore
				}
			}
		}
	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		
		Runnable task = new Runnable() {
			@Override
			public void run() {
				// 任务逻辑代码部分.
				tranforeFile();
			}
		};
		Trigger trigger = new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 任务触发，可修改任务的执行周期.
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExec = trigger.nextExecutionTime(triggerContext);
				return nextExec;
			}
		};
		taskRegistrar.addTriggerTask(task, trigger);
	}
}